from django.db import models
from django.conf import settings
from django.utils.text import slugify
from django.urls import reverse


# Create your models here.

class Image(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='images_created', on_delete=models.CASCADE,
                             verbose_name='用户'),
    title = models.CharField(max_length=200, verbose_name='图片标题')
    slug = models.SlugField(max_length=200, blank=True, verbose_name='图片简称')
    url = models.URLField(verbose_name='图片地址')
    image = models.ImageField(upload_to='images/%Y/%m/%d', verbose_name='图片')
    desc = models.TextField(blank=True, verbose_name='图片简介')
    created = models.DateField(auto_now_add=True, db_index=True, verbose_name='创建时间')
    users_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='images_liked', blank=True,
                                        verbose_name='收藏用户')
    total_likes = models.PositiveIntegerField(db_index=True, default=0)

    def __str__(self):
        return self.title

    # 重写Image模型的save()方法，使图片在保存到数据库时，自动根据title字段生成slug字段的内容
    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super(Image, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('images:detail', args=[self.id, self.slug])

    class Meta:
        verbose_name = '图片管理'
        verbose_name_plural = verbose_name
